//
//  WebNewsViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-25.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "WebNewsViewController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "MainTabBarController.h"
#import "LoginViewController.h"
#import "ShareWebViewController.h"
@interface WebNewsViewController ()

@end

@implementation WebNewsViewController
@synthesize m_WebURL;
@synthesize m_HttpURL;
@synthesize m_NewsID;
- (id)init
{
    if (self =[super init]) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc
{
    [_ShareAction release];
    [m_NewsID release];
    [_CusWebView release];
    [m_WebURL release];
    [m_HttpURL release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor colorWithRed:240/255.f green:240/255.f blue:240/255.f alpha:1]];
    UIButton* tBackBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [tBackBtt setImage:[UIImage imageNamed:@"news_back.png"] forState:UIControlStateNormal];
    tBackBtt.frame =CGRectMake(0, 6, 50, 30);
    [tBackBtt addTarget:self action:@selector(toBackPop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tBackBtt];
    
    UIImageView* tLineImgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 39, 290, 2)];
    [tLineImgView setImage:[UIImage imageNamed:@"line.png"]];
    [self.view addSubview:tLineImgView];
    [tLineImgView release];
    
    UIImageView* tDLineImgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, self.view.frame.size.height-49, 290, 2)];
    [tDLineImgView setImage:[UIImage imageNamed:@"line.png"]];
    [self.view addSubview:tDLineImgView];
    [tDLineImgView release];
    
    //分享，收藏
    UIImageView* tFXImgView = [[UIImageView alloc] initWithFrame:CGRectMake(180, self.view.frame.size.height-49+12, 26, 26)];
    [tFXImgView setImage:[UIImage imageNamed:@"share.png"]];
    [self.view addSubview:tFXImgView];
    [tFXImgView release];
    
    UIImageView* tFavImgView = [[UIImageView alloc] initWithFrame:CGRectMake(242, self.view.frame.size.height-49+12, 26, 26)];
    [tFavImgView setImage:[UIImage imageNamed:@"fav.png"]];
    [self.view addSubview:tFavImgView];
    [tFavImgView release];
    
    UILabel* tShareLab = [[UILabel alloc] initWithFrame:CGRectMake(210, self.view.frame.size.height-49+16, 30, 20)];
    [tShareLab setBackgroundColor:[UIColor clearColor]];
    [tShareLab setText:@"分享"];
    [tShareLab setFont:[UIFont systemFontOfSize:13]];
    [tShareLab setTextColor:[UIColor colorWithRed:107/255.f green:108/255.f blue:109/255.f alpha:1]];
    [self.view addSubview:tShareLab];
    [tShareLab release];
    
    UILabel* tFavLab = [[UILabel alloc] initWithFrame:CGRectMake(272, self.view.frame.size.height-49+16, 30, 20)];
    [tFavLab setBackgroundColor:[UIColor clearColor]];
    [tFavLab setText:@"收藏"];
    [tFavLab setFont:[UIFont systemFontOfSize:13]];
    [tFavLab setTextColor:[UIColor colorWithRed:107/255.f green:108/255.f blue:109/255.f alpha:1]];
    [self.view addSubview:tFavLab];
    [tFavLab release];
    
    UIButton* tShareBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    tShareBtt.frame =CGRectMake(180, self.view.frame.size.height-49+12, 60, 26);
    [tShareBtt addTarget:self action:@selector(shareBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tShareBtt];
    
    UIButton* tFavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    tFavBtt.frame =CGRectMake(242, self.view.frame.size.height-49+12, 60, 26);
    [tFavBtt addTarget:self action:@selector(favBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tFavBtt];
    
    _CusWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 43, 320, self.view.frame.size.height-94)];
    
    [_CusWebView setBackgroundColor:[UIColor colorWithRed:240/255.f green:240/255.f blue:240/255.f alpha:1]];
    [self.view addSubview:_CusWebView];
    
    for (id tObject in _CusWebView.subviews) {
        if ([tObject isKindOfClass:[UIScrollView class]]) {
            ((UIScrollView*)tObject).showsHorizontalScrollIndicator =NO;
        }
    }
    
    _ShareAction = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"分享到新浪微博",@"分享到腾讯微博", nil];
    
    if ([m_WebURL length] > 0) {
        [_CusWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:m_WebURL]]];
    }else{
        [self requestNewDetailData];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden =YES;
    
}
-(void) viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}

-(void) toBackPop
{
    [self.navigationController popViewControllerAnimated:YES];
}

//我要分享
-(void) shareBttPressed
{
    [_ShareAction showFromTabBar:self.tabBarController.tabBar];
}
//我要收藏
-(void) favBttPressed
{
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    if ( tMainTabController.m_UserDic != nil) {
        [self addHudLoad];
        NSDictionary* tDataDic = [tMainTabController.m_UserDic objectForKey:@"data"];
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=fav&cur_user_id=%@&target=news&target_id=%@",RequestCurrentURL,[tDataDic objectForKey:@"user_id"],m_NewsID];
        ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
        [tRequestPage setDelegate:self];
        [tRequestPage setDidFailSelector:@selector(requestNDetailFail:)];
        [tRequestPage setDidFinishSelector:@selector(requestFavFinish:)];
        [tRequestPage startAsynchronous];
    }else{
        LoginViewController* tLogin = [[LoginViewController alloc] init];
        tLogin.pushtype = 0;
        tLogin.hidesBottomBarWhenPushed = YES;
        tLogin.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tLogin animated:YES];
        [tLogin release];
    }
}

-(void) requestFavFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            if ([[tRealDataDic objectForKey:@"result"] intValue] == 1) {
                [tAppDel showWithCustomView:@"收藏成功" detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"收藏失败" detailText:@"" isCue:-1 delayTime:2];
            }
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:-1 delayTime:2];
            }
        }
    }
    [self hudWasHidden:nil];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}


///新闻详细
-(void) requestNewDetailData
{
    [self addHudLoad];
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:m_HttpURL]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestNDetailFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestNDetailFinish:)];
    [tRequestPage startAsynchronous];
}
-(void) requestNDetailFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestNDetailFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            [_CusWebView loadHTMLString:[tRealDataDic objectForKey:@"content"] baseURL:nil];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

#pragma mark-
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0 || buttonIndex == 1) {
        ShareWebViewController* tShareWebVC = [[ShareWebViewController alloc] init];
        tShareWebVC.navigationItem.hidesBackButton =YES;
        tShareWebVC.m_ShareType = buttonIndex;
        tShareWebVC.m_ContentID = m_NewsID;
        [self.navigationController pushViewController:tShareWebVC animated:YES];
        [tShareWebVC release];
    }
}
@end
